package com.me.bbs.service.impl;

import com.me.bbs.common.SessionUtils;
import com.me.bbs.entity.Post;
import com.me.bbs.entity.PostLike;
import com.me.bbs.entity.User;
import com.me.bbs.mapper.PostLikeMapper;
import com.me.bbs.service.IPostLikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.me.bbs.service.IPostService;
import com.me.bbs.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lm
 * @since 2023-01-09
 */
@Service
public class PostLikeServiceImpl extends ServiceImpl<PostLikeMapper, PostLike> implements IPostLikeService {
    @Resource
    IPostService postService;
    @Resource
    IUserService userService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePostLike(Long postId) throws Exception {
        Long uid = (Long) SessionUtils.getAttribute("user");
        PostLike postLike = this.lambdaQuery()
                .eq(PostLike::getUser, uid)
                .eq(PostLike::getPost, postId)
                .one();
        if(postLike != null) return;
        postLike = new PostLike();
        postLike.setPost(postId);
        postLike.setUser(uid);
        boolean save = this.save(postLike);
        if(!save) throw new Exception(this.getClass().getName() + "保存出错");
        postService.lambdaUpdate()
                .eq(Post::getPostId,postId)
                .setSql("like_count = like_count + 1")
                .update();
        userService.lambdaUpdate()
                .eq(User::getUserId, uid)
                .setSql("like_count = like_count + 1")
                .update();

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delPostLike(Long postId) throws Exception {
        Long uid = (Long) SessionUtils.getAttribute("user");
        boolean remove = this.lambdaUpdate()
                .eq(PostLike::getUser, uid)
                .eq(PostLike::getPost, postId)
                .remove();
        if(!remove) throw new Exception("删除错误");
        postService.lambdaUpdate()
                .eq(Post::getPostId,postId)
                .setSql("like_count = like_count - 1")
                .update();
        userService.lambdaUpdate()
                .eq(User::getUserId, uid)
                .setSql("like_count = like_count - 1")
                .update();
    }
}
